package com.harmonk.firstscene.ui.model

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.harmonk.firstscene.FirstSceneApplication
import com.harmonk.firstscene.db.entity.EventWithAll
import kotlinx.coroutines.launch

class EventWithAllViewModel(application: Application) : AndroidViewModel(application) {
    private val eventWithAllRepository = (application as FirstSceneApplication).eventWithAllRepository

    private val _currentEventWithAll = MutableLiveData<EventWithAll>()
    val currentEventWithAll: LiveData<EventWithAll> = _currentEventWithAll

    fun getEventWithAllById(id: Long) {
        viewModelScope.launch {
            try {
                eventWithAllRepository.getEventWithAll(id).collect { currentEventWithAll ->
                    _currentEventWithAll.postValue(currentEventWithAll)
                }
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }
}

class EventWithAllViewModelFactory(private val application: Application) : ViewModelProvider.Factory {
    override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(EventWithAllViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return EventWithAllViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}